package com.shujia.scala

import scala.io.{BufferedSource, Source}

object Demo36Student {
  def main(args: Array[String]): Unit = {
    /**
      * 4、统计偏科最严重的前100名学生
      *
      * 1、
      *
      */


    //1、读取文件
    val source: BufferedSource = Source.fromFile("data/score.txt")
    val scores: List[String] = source.getLines().toList

    //2、取出学号和分数
    val idAndScore: List[(String, Double)] = scores.map(sco => {
      val split: Array[String] = sco.split(",")
      val id: String = split(0)
      val score: Double = split(2).toDouble
      (id, score)
    })

    //3、按照学号分组
    val groupBy: Map[String, List[(String, Double)]] = idAndScore.groupBy(kv => kv._1)


    //4、计算方差
    val result: List[(String, List[(String, Double)], Double)] = groupBy
      .toList
      .map {
        case (id: String, idAndSco: List[(String, Double)]) =>
          //取出学生各科的分数
          val scores: List[Double] = idAndSco.map(kv => kv._2)

          //计算平均值
          val avg: Double = scores.sum / scores.length

          //带入公式计算方差
          val std: Double = scores.map(sco => (sco - avg) * (sco - avg)).sum / scores.length


          //返回数据
          (id, idAndSco, std)
      }

    //5、按照方差排序
    val sort: List[(String, List[(String, Double)], Double)] = result.sortBy(kv => -kv._3)

    //6、取前100
    val top100: List[(String, List[(String, Double)], Double)] = sort.take(100)


    top100.foreach(println)

  }

}
